<?php

class Workset_Controller_Action_Helper_Utils extends Zend_Controller_Action_Helper_Abstract {

    function stripPrefix($fields, $prefix) {
        $prefix = $prefix.'_';
        foreach ($fields as $key => $value) {
            if (0 === strpos($key, $prefix)) {
                $newKey = substr($key, strlen($prefix));
                unset($fields[$key]);
                $fields[$newKey] = $value;
            }
        }
        return $fields;
    }

    function addPrefix($fields, $prefix) {
        $prefix = $prefix.'_';
        foreach ($fields as $key => $value) {
            $newKey = $prefix.$key;
            unset($fields[$key]);
            $fields[$newKey] = $value;
        }
        return $fields;
    }

    function arrayStraighten($array, $possibleKey = null, $maxDepth = 1000) {
        $result = array();

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                if ($maxDepth > 1) {
                    $value = $this->arrayStraighten($value, $possibleKey, $maxDepth - 1);
                    $result += $value;
                    continue;
                }

                if (null !== $possibleKey && array_key_exists($possibleKey, $value)) {
                    $key = $value[$possibleKey];
                    if (isInt($key)) {
                        $key = (int)$key;
                    }
                }
            }

            $result[$key] = $value;
        }

        return $result;
    }

    function arrayValues(array $array, $possibleKey = null, $maxDepth = 1000) {
        $result = array();

        if ($maxDepth <= 0 || null === $possibleKey) {
            return array_keys($array);
        }

        foreach ($array as $key => $value) {
            if (is_array($value)) {
                if ($maxDepth == 1 && isset($value[$possibleKey])) {
                   $result[] = $value[$possibleKey];
                } else {
                   $value = $this->arrayValues($value, $possibleKey, $maxDepth - 1);
                   $result += $value;
                }
            }
        }

        return $result;
    }

    function params($value) {
        if (is_array($value)) {
            return http_build_query($value);
        } else {
            $result = array();
            parse_str((string)$value, $result);
            return $result;
        }
    }

}

?>